package com.demo;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class RabbitMQConsumer {

    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void processMessage(byte[] message,
                               @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                               @Header("amqp_consumerTag") String consumerTag,
                               Channel channel) throws IOException {
        try {
            // 处理消息
            String messageStr = new String(message);
            System.out.println("接收到的消息: " + messageStr);

            // 手动确认消息
            channel.basicAck(deliveryTag, false); //是否批量确认
        } catch (Exception e) {
            e.printStackTrace();
            // 如果处理失败，可以选择拒绝消息或者重新入队
            channel.basicNack(deliveryTag, false, true);//第二是否批量 第三个是是否重新入队
        }
    }
}